package com.qfhd.soft.cjzcore.TaskCenter.ADModel;

import androidx.annotation.NonNull;

import com.qfhd.soft.cjzcore.Core.CJJsonUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

public class ADModel {
    public int ggPalce;
    public int ggStyle;
    public ArrayList<ADResourceModel> resources = new ArrayList<ADResourceModel>();

    public static ADModel getADModelByJSONObject(JSONObject obj){
        ADModel model = new ADModel();
        model.ggPalce = CJJsonUtils.getValueFromKey_int(obj,"ggPlace");
        model.ggStyle = CJJsonUtils.getValueFromKey_int(obj,"ggStyle");
        try {
            model.resources = ADResourceModel.getArrayADResourceModel(obj.getJSONArray("ggWeight"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return model;
    }

    public static ADModel getModelByGGplace(ArrayList<ADModel> array,int ggPalce){
        for(ADModel model : array){
            if(model.ggPalce == ggPalce){
                return model;
            }
        }
        return null;
    }

    public static int getResourceTypeFromModel(ADModel model){
        int random = getRadom(getMax(model));
        return getType(random,model);
    }

    private static int getRadom(int max){
        return ThreadLocalRandom.current().nextInt(0, max) + 1;
    }

    private static int getType(int random,ADModel model){
        int tmp = 0;
        for(int i=0; i<model.resources.size(); i++){
            ADResourceModel item = model.resources.get(i);
            tmp += item.weight;
            if(tmp >= random){
                return item.ggResource;
            }
        }
        return 0;
    }

    private static int getMax(ADModel model){
        int tmp = 0;
        for(int i=0; i<model.resources.size(); i++){
            ADResourceModel item = model.resources.get(i);
            tmp += item.weight;
        }
        return tmp;
    }

    @NonNull
    @Override
    public String toString() {
        String tmp = "ggPalce :" + ggPalce + " ggStyle:" + ggStyle;
        for(ADResourceModel model : resources){
            tmp += "\n" + model.toString();
        }
        return tmp;
    }
}
